import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { connect } from 'tls';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { Component, Input, OnInit } from '@angular/core';
import { EventService } from 'src/app/shared/service/event.service';
import { AlertController } from '@ionic/angular';

@Component({
  selector: 'app-shopping-car',
  templateUrl: './shopping-car.component.html',
  styleUrls: ['./shopping-car.component.scss'],
})
export class ShoppingCarComponent implements OnInit {
  @Input() tagData: any;
  checkedAll = false;
  isOpen = false;
  dataIndex = -1;
  ids: any;
  saleTotal = 0;
  oTotal = 0;
  commonIds: any[];
  priceArr: any[];
  edit = false;
  writeOffId: any; // 核销ID
  timer: any;
  constructor(
    private httpService: HttpService,
    public appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private eventService: EventService,
    public alertController: AlertController
  ) { }

  ngOnInit() {

    // 2024.04.11 add by andrew.wen for 购物车弹窗
    if (this.tagData.name.includes('_shopGoodsCart')) {
      if (this.tagData && this.tagData.data && this.tagData.data.data && this.tagData.data.data.length > 0) {
        this.appGlobalService.settleCartIds = new Set();
        if (this.tagData.data.data[0].showCheckedAllLabel !== undefined) {
          this.appGlobalService.modalCartNum = 0;
          // tslint:disable-next-line:prefer-for-of
          for (let index = 0; index < this.tagData.data.data.length; index++) {
            const element = this.tagData.data.data[index];
            if (element.checked === 'true') {
              this.appGlobalService.modalCartNum += 1;
              this.appGlobalService.settleCartIds.add(element.id);
            }
          }
        }
      } else {
        this.appGlobalService.modalCartNum = 0;
        this.appGlobalService.settleCartPrice = 0;
        this.appGlobalService.settleCartIds = new Set();
      }
    }




    if (this.tagData.data.submit && this.tagData.data.submit.content) {
      this.tagData.data.submit.content.pageNo = 2; // page返回初始PageNo 1 ;为了直接是否后面返回submit请求下一页
    }




    if (this.tagData.data.headDiv) {
      this.tagData.data.headDiv.isOpen = true;
    }



    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    if (this.eventService.eventEmit.listenerCount('chooseAll') > 0) {
      this.eventService.eventEmit.removeListener('chooseAll');
    }
    this.eventService.eventEmit.on('auditNow', res => {
      console.log(res);
      this.commonIds = [];
      this.priceArr = [];
      this.tagData.data.data.forEach(element => {
        if (element.checked) {
          this.commonIds.push(element.id);
          this.priceArr.push(0);
        }
      });
      if (this.commonIds.length === 0) {
        this.ids = '';
        return;
      }
      this.ids = this.commonIds.join(',');

      if (res.target) {
        if (res.beforeSubmit) {
          this.submitData(res);
        } else {
          this.showModal(res);
        }

      } else {
        // submit
        this.presentAlertWithMsgBtn(res);

      }

    });
    // 全选
    this.eventService.eventEmit.on('chooseAll', res => {
      if (res) {
        this.checkedAll = true;
        this.tagData.data.data.forEach(element => {

          element.checked = true;
          element.checkedGroup = true;


        });
      } else {
        this.tagData.data.data.forEach(element => {

          element.checked = false;
          element.checkedGroup = false;

        });
      }
      this.checkAll();
    });

    // 显示删除按钮
    if (this.eventService.eventEmit.listenerCount('manageShopping') > 0) {
      this.eventService.eventEmit.removeListener('manageShopping');
    }
    this.eventService.eventEmit.on('manageShopping', res => {
      this.edit = !this.edit;
    });

    if (this.eventService.eventEmit.listenerCount('emitWriteOffList') > 0) {
      this.eventService.eventEmit.removeListener('emitWriteOffList');
    }
    this.eventService.eventEmit.on('emitWriteOffList', result => {
      this.getWriteOffId(result);
      result.submit.content[result.id] = this.writeOffId;
      const params = {
        content: result.submit.content,
        id: result.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };

      this.httpService.post("application/submit", params, res => {
        if (res.success) {
          if (result.needRefresh !== undefined) {
            localStorage.setItem('needRefresh', 'true');
            this.appGlobalService.popTarget();
          }
        } else {
          this.appGlobalService.showToast(res.message, 1500, "middle");
        }
      });
    });

  }


  async presentAlertWithMsgBtn(submit, i?) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {
            submit.content.shop_goods_cart_id = this.ids;
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                if (i !== undefined) {
                  this.tagData.data.data.splice(i, 1);
                  if (this.appGlobalService.floatShoppingCartObj["isShow"] === true) {
                    // tslint:disable-next-line: max-line-length
                    this.appGlobalService.floatShoppingCartObj.count = this.appGlobalService.floatShoppingCartObj.count - 1;
                  }
                  that.checkAll();
                  localStorage.setItem('needRefresh', 'true');
                } else {
                  that.delItems();
                }
              }
              if (res.message.length > 0) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }


  submitData(link) {
    if (link.beforeSubmit.content.listKey) {
      link.beforeSubmit.content[link.beforeSubmit.content.listKey] = this.ids;
    } else {
      link.beforeSubmit.content.shop_goods_cart_id = this.ids;
    }
    if (link.beforeSubmit.content && link.beforeSubmit.content.price) {
      link.beforeSubmit.content[link.beforeSubmit.content.price] = this.priceArr.join(',');
    }
    const params = {
      content: link.beforeSubmit.content,
      id: link.beforeSubmit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {

      if (res.success) {
        this.appGlobalService.orderRealPayAmount = 0; //  清空购物车总价格
        localStorage.setItem('needRefresh', 'true');
        if (res.data.eventResult && link.params && link.params.eventReturnParam) {
          link.params[link.params.eventReturnParam] = res.data.eventResult;
        }
        if (res.data.eventResult && link.params && link.params.eventResult) {
          link.params[link.params.eventResult] = res.data.eventResult;
        }
        this.showModal(link);
      }
      if (res.message.length > 0) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }

    });
  }

  showModal(link) {
    if (link) {
      const that = this;
      link.params.shop_goods_cart_id = this.ids;
      this.pageModalService.openPage(link, '', result => {
        if (result) {
          // that.updateItem();
        }
      });
    }
  }

  updateItem(id?) {

    if (this.checkedAll) {
      this.appGlobalService.reloadCurrentPage();
      return;
    }
    const that = this;
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {};
    }
    page.params.id = id;
    this.httpService.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'myShopCarListTag' && element.data && element.data.data) {
          element.data.data.forEach(newItem => {
            that.tagData.data.data.forEach(oItem => {
              if (oItem.id === newItem.id) {
                const index = that.tagData.data.data.indexOf(oItem);
                that.tagData.data.data.splice(index, 1, newItem); // 替换
              }
            });
          });
        }
        that.checkAll();

      });
    });
  }
  delItems() {

    for (let i = this.tagData.data.data.length - 1; i >= 0; i--) {
      if (this.tagData.data.data[i].checked) {
        this.tagData.data.data.splice(i, 1);
      }
    }
    this.ids = '';
    // 1.6.29
    if (this.appGlobalService.floatShoppingCartObj["isShow"] === true) {
      // tslint:disable-next-line: max-line-length
      this.appGlobalService.floatShoppingCartObj.count = this.appGlobalService.floatShoppingCartObj.count - this.commonIds.length;
    }
    if ((this.pageModalService.chatService.getCartItemCount() - this.commonIds.length) < 0) {
      this.pageModalService.chatService.setCartItemCount(0, true);
    } else {
      // tslint:disable-next-line:max-line-length
      this.pageModalService.chatService.setCartItemCount((this.pageModalService.chatService.getCartItemCount() - this.commonIds.length), true);
    }
    this.checkAll();
    localStorage.setItem('needRefresh', 'true');
  }
  sub(event, submit, item, i, index) {
    let count: any;
    item.thirdRowRight.inputBox.label = item.thirdRowRight.inputBox.label * 1;
    let subType = '';
    if (i === 0) {
      subType = 'subtraction';
      // 如果有 起批量 起购量   11.13 新增需求‘商品减到小于1直接删除商品’
      if (item.thirdRowRight.minBatchCount && Number(item.thirdRowRight.inputBox.label) !== 1) {
        if (item.thirdRowRight.minCount && item.thirdRowRight.inputBox.label < item.thirdRowRight.minCount) {
          item.thirdRowRight.inputBox.label = item.thirdRowRight.minCount;
        } else if (Number(item.thirdRowRight.inputBox.label) === Number(item.thirdRowRight.minCount)) {
          if ((item.thirdRowRight.inputBox.label - 1) <= 0) {
            this.delItem(event, item, index, 'delNoPrompt');
          } else {
            this.appGlobalService.showToast('已达到最低购买量~', 1500, "top");
          }
        } else {
          count = item.thirdRowRight.inputBox.label - item.thirdRowRight.minBatchCount;
        }
      } else {
        item.thirdRowRight.inputBox.label -= 1;
      }

      if (item.thirdRowRight.inputBox.label <= 0) {
        this.delItem(event, item, index, 'delNoPrompt');
        event.stopPropagation();
        return;
      }

    } else if (i === 1) {
      subType = 'addtion';
      if (item.thirdRowRight.inventory && item.thirdRowRight.inputBox.label >= item.thirdRowRight.inventory) {
        item.thirdRowRight.inputBox.label = item.thirdRowRight.inventory;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          if (item.thirdRowRight.message) {
            this.appGlobalService.showToast(item.thirdRowRight.message, 1500, 'top');
          } else {
            this.appGlobalService.showToast('库存不足~', 1500, 'top');
          }
        }, 100);
        event.stopPropagation();
        return;
      } else if (item.thirdRowRight.minBatchCount) {
        item.thirdRowRight.inputBox.label = item.thirdRowRight.inputBox.label + Number(item.thirdRowRight.minBatchCount);
      } else {
        item.thirdRowRight.inputBox.label += 1;
      }
    }
    if (count) {
      submit.content.count = count;
    } else {
      submit.content.count = item.thirdRowRight.inputBox.label;
    }
    console.log('current num :' + item.thirdRowRight.inputBox.label);
    const params = {
      content: submit.content,
      id: submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {

      if (!res.success) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      } else {

        // 2024.04.12 发送emit更新
        if (this.tagData.name.includes('_shopGoodsCart')) {
          res.subType = subType;
          // 发送emit 更新商品数量
          this.eventService.eventEmit.emit('refreshCartInfo', res);
        }
        if (count) {
          item.thirdRowRight.inputBox.label = item.thirdRowRight.inputBox.label - item.thirdRowRight.minBatchCount;
          this.checkAll();
        }
      }
    });
    if (!count) {
      this.checkAll();
    }
    event.stopPropagation();
  }

  openPage(link, event?, index?) {
    if (event && event.target.tagName === 'INPUT') {

    } else {
      this.pageModalService.openPage(link, '', res => {
        if (res) {
          if (index >= 0) {
            this.updateItem(this.tagData.data.data(index).id);
          }
        }
      });
      if (event) {
        event.stopPropagation();
      }
    }

  }
  // 上滑加载
  loadMoreData(event) {
    if (this.tagData.data.data.length >= this.tagData.pageTotal) {
      event.target.disabled = true;
      // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
      // event.complete();
      return;
    }
    if (this.tagData.data.submit) {

      this.tagData.data.submit.sessionId = localStorage.getItem("sessionId");
    }

    this.httpService.post(
      "application/submit",
      this.tagData.data.submit,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          this.tagData.data.submit = res.data.submit;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.tagData.data.data.push(item);
              this.checkAll();
            });
          } else {
            event.target.disabled = true;
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
          }
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {

        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }
  closeOpen() {
    this.isOpen = !this.isOpen;
    this.eventService.eventEmit.emit('isOpen', this.isOpen);
  }
  // 检查是否已经全选 价格合计
  checkAll() {
    let all = true;
    try {
      this.tagData.data.data.forEach(element => {
        if (!element.checked) {
          all = false;
          this.eventService.eventEmit.emit('chooseAllResult', all);
          throw new Error('break');
        }
      });
      this.checkedAll = all;
      this.eventService.eventEmit.emit('chooseAllResult', all);
    } catch (error) {
      if (error.message !== "break") { throw error; }
    }

    this.saleTotal = 0;
    this.oTotal = 0;
    this.appGlobalService.settleCartIds = new Set();
    this.tagData.data.data.forEach(element => {

      if (element.checked) {
        this.saleTotal += Number(element.thirdRowRight.inputBox.label) * Number(element.thirdRowLeft.secondText.label);
        if (element.fourthRowLeft && element.fourthRowLeft.secondText && element.fourthRowLeft.secondText.label) {
          this.oTotal += Number(element.thirdRowRight.inputBox.label) * Number(element.fourthRowLeft.secondText.label);
        }
        this.appGlobalService.settleCartIds.add(element.id);
      }
    });
    this.saleTotal = Math.fround(this.saleTotal * 100) / 100;
    this.oTotal = Math.fround(this.oTotal * 100) / 100;
    this.eventService.eventEmit.emit('Total', { saleTotal: this.saleTotal, oTotal: this.oTotal });





    // 2024.04.11 add by andrew.wen for 弹窗购物车
    if (this.tagData && this.tagData.data && this.tagData.data.data && this.tagData.data.data.length > 0) {
      if (this.tagData.data.data[0].showCheckedAllLabel !== undefined) {
        this.appGlobalService.settleCartPrice = this.saleTotal;
        if (this.appGlobalService.modalCartNum < 0) {
          this.appGlobalService.modalCartNum = 0;
          this.appGlobalService.settleCartIds = new Set();
        }
      }
    }


  }

  checkGroupAll(event, item) {
    if (item.showCheckedAllLabel) {
      this.appGlobalService.modalCartNum = 0;
    }
    item.checkedGroup = !item.checkedGroup;
    if (item.checkedGroup) {
      this.tagData.data.data.forEach(element => {
        if (element.type === item.type) {
          element.checked = true;
          if (item.showCheckedAllLabel) {
            this.appGlobalService.modalCartNum += 1;
          }
        }
      });
    } else {
      this.tagData.data.data.forEach(element => {
        if (element.type === item.type) {
          element.checked = false;
          if (item.showCheckedAllLabel) {
            this.appGlobalService.modalCartNum -= 1;
          }
        }
      });
    }
    this.checkAll();
    event.stopPropagation();
  }
  checkItem(event, item) {
    item.checked = !item.checked;

    if (item.checked) {
      let all = true;
      try {
        this.tagData.data.data.forEach(element => {
          if (element.type === item.type && !element.checked) {
            all = false;
            throw new Error('break');
          }
        });

      } catch (error) {
        if (error.message !== "break") { throw error; }
      }
      if (!all) {
        this.tagData.data.data.forEach(element => {
          if (element.type === item.type) {
            element.checkedGroup = false;
          }
        });
      } else {
        this.tagData.data.data.forEach(element => {
          if (element.type === item.type) {
            element.checkedGroup = true;
          }
        });
      }


    } else {
      this.tagData.data.data.forEach(element => {
        if (element.type === item.type) {
          element.checkedGroup = false;
        }
      });
    }

    //2024.04.11 add by andrew.wen for 
    if (item.showCheckedAllLabel) {
      if (item.checked) {
        this.appGlobalService.modalCartNum += 1;
      } else {
        this.appGlobalService.modalCartNum -= 1;
      }

    }

    this.checkAll();
    event.stopPropagation();
  }

  changeValue(event, item) {
    let timer = setTimeout(() => {
      event.detail.value = event.detail.value - 0;
      if (event.detail.value > Number(item.thirdRowRight.inventory)) {
        item.thirdRowRight.inputBox.label = Number(item.thirdRowRight.inventory);
        this.appGlobalService.showToast('已达到最大可以购买数量', 1500, 'top');
        event.stopPropagation();
      }
      clearTimeout(timer);
    }, 0);
  }
  inutValue(event, item) {
    if (item.thirdRowRight.inputBox.label > 0) {
      // 最低起购量 minCount    起批量 minBatchCount
      if (item.thirdRowRight.minCount && item.thirdRowRight.minBatchCount) {
        if (item.thirdRowRight.inputBox.label < item.thirdRowRight.minCount || (item.thirdRowRight.inputBox.label - item.thirdRowRight.minCount) % item.thirdRowRight.minBatchCount !== 0) {
          item.thirdRowRight.inputBox.label = item.thirdRowRight.minCount;
          this.appGlobalService.showToast('购买数量不符，请通过点击加减数量', 2000, 'middle');
        }
      }
    } else if (item.thirdRowRight.inputBox.label <= 0 || item.thirdRowRight.inputBox.label === null) {
      // 如果有 最低订购数量
      if (item.thirdRowRight.minCount) {
        item.thirdRowRight.inputBox.label = item.thirdRowRight.minCount;
        this.appGlobalService.showToast('购买数量不符，请通过点击加减数量', 2000, 'middle');
      } else {
        item.thirdRowRight.inputBox.label = 1;
      }
    }
    if (item.thirdRowRight && item.thirdRowRight.submit && item.thirdRowRight.submit.content) {
      item.thirdRowRight.submit.content.count = item.thirdRowRight.inputBox.label;
      console.log('current num :' + item.thirdRowRight.inputBox.label);

      const params = {
        content: item.thirdRowRight.submit.content,
        id: item.thirdRowRight.submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {

        if (!res.success) {
          this.appGlobalService.showToast(res.message, 1500, "middle");
        }
      });
    }
    this.checkAll();
  }
  delItem(e, item, i, delNoPrompt?) {
    if (e) {
      e.stopPropagation();
    }
    if (!this.appGlobalService.shoppingCarId) {
      this.eventService.eventEmit.emit("needManageShopping", 1); // 为了获取购物车id
    }

    this.ids = item.id;
    const res = item.delete.submitButton;
    if (this.appGlobalService.shoppingCarId) {
      res.id = this.appGlobalService.shoppingCarId;
    }
    res.content = {};
    // tslint:disable-next-line: no-string-literal
    res["content"]["shop_goods_cart_id"] = "";
    if (delNoPrompt && delNoPrompt === 'delNoPrompt') {
      this.delNoPrompt(res, i);
    } else {
      this.presentAlertWithMsgBtn(res, i);
    }
  }
  getInterger(value) {
    return parseInt(value, 10);
  }
  // 删除单条商品，不提示’是否删除‘
  delNoPrompt(submit, i) {
    submit.content.shop_goods_cart_id = this.ids;
    const params = {
      content: submit.content,
      id: submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        if (i !== undefined) {
          this.tagData.data.data.splice(i, 1);
          if (this.appGlobalService.floatShoppingCartObj["isShow"] === true) {
            // tslint:disable-next-line: max-line-length
            this.appGlobalService.floatShoppingCartObj.count = this.appGlobalService.floatShoppingCartObj.count - 1;
          }
          this.checkAll();
          localStorage.setItem('needRefresh', 'true');
        } else {
          this.delItems();
        }
      }
      if (res.message.length > 0) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
    });
  }

  getWriteOffId(res) {
    this.writeOffId = '';
    if (res.isAllData) {
      this.tagData.data.data.forEach(element => {
        if (this.writeOffId) {
          this.writeOffId += '#' + element.id + '_' + element.thirdRowLeft.thirdText.value;
        } else {
          this.writeOffId += element.id + '_' + element.thirdRowLeft.thirdText.value;
        }
      });
    } else {
      this.tagData.data.data.forEach(element => {
        if (element.checked) {
          if (this.writeOffId) {
            this.writeOffId += '#' + element.id + '_' + element.thirdRowRight.inputBox.label;
          } else {
            this.writeOffId += element.id + '_' + element.thirdRowRight.inputBox.label;
          }
        }
      });
    }
  }
}

